package com.hqyj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hqyj.dao.PracticeMapper;
import com.hqyj.dao.SamplePracticeInfoMapper;
import com.hqyj.dao.ScoreManagementMapper;
import com.hqyj.pojo.*;
import com.hqyj.dao.SamplepaperMapper;
import com.hqyj.service.ISamplepaperService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 试卷表 服务实现类
 * </p>
 *
 * @author rock
 * @since 2021-11-18
 */
@Service
public class SamplepaperServiceImpl implements ISamplepaperService {
    @Autowired
    PracticeMapper practiceMapper;
    @Autowired
    SamplepaperMapper samplepaperMapper;
    @Autowired
    SamplePracticeInfoMapper samplePracticeInfoMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public HashMap<String, Object> select(Samplepaper samplepaper) {
        HashMap<String, Object> map = new HashMap<>();
        // 分页对象
        Page<Samplepaper> samplepaperPage = new Page<>(samplepaper.getPage(), samplepaper.getRow());
        //System.err.println("Exampaper"+exampaper);
        // 条件构造器
        QueryWrapper<Samplepaper> samplepaperQueryWrapper = new QueryWrapper<>();
        // 条件查询
        samplepaperQueryWrapper.eq(samplepaper.getSampleId() != null, "sample_id", samplepaper.getSampleId());
        samplepaperQueryWrapper.like(
                (!StringUtils.isEmpty(samplepaper.getSampleTitle())) && samplepaper.getSampleTitle() != null,
                "sample_title", samplepaper.getSampleTitle());

        // 定义当前页的 key
        String curKey = "samplePaper:list:" + samplepaper.getPage() + ":" + samplepaper.getRow() + ":" + samplepaper.getSampleTitle() + ":";
        // 总条数
        String totalKey = "samplePaper:total" + ":" + samplepaper.getSampleTitle();

        // 判断当前页在 Redis 中所有是否有
        Object obj = redisTemplate.opsForValue().get(curKey);
        if (obj != null) {
            map.put("info", "success");
            map.put("list", redisTemplate.opsForValue().get(curKey));
            map.put("total", redisTemplate.opsForValue().get(totalKey));
        } else {
            // 获取分页结果集
            Page<Samplepaper> page = samplepaperMapper.selectPage(samplepaperPage, samplepaperQueryWrapper);

            // 获取返回的分页结果集对象
            map.put("info", "success");
            map.put("list", page.getRecords());
            map.put("total", page.getTotal());

            // 添加数据到 Redis 缓存中
            redisTemplate.opsForValue().set(curKey, page.getRecords(), 5, TimeUnit.SECONDS);
            redisTemplate.opsForValue().set(totalKey, page.getTotal(), 5, TimeUnit.SECONDS);
        }

        return map;
    }

    @Override
    public HashMap<String, Object> randGeneratePaper(Samplepaper samplepaper) {

        HashMap<String, Object> map = new HashMap<>();

        // 模拟试题的生成
        // 设置试卷生成时间
        samplepaper.setSampleCreatetime(new Date());
        // 设置试卷名称
        samplepaper.setSampleTitle(samplepaper.getSampleTitle() + System.currentTimeMillis());
        // 生成试卷
        int insert = samplepaperMapper.insert(samplepaper);


        //  获取最大自增ID
        samplepaper.setSampleId(samplepaperMapper.getMAXId());

        // 单选题列表
        List<Practice> singleList = practiceMapper.selectList(
                new QueryWrapper<Practice>().like(true, "practice_type", "单选题"));
        // 判断题列表
        List<Practice> judgeList = practiceMapper.selectList(
                new QueryWrapper<Practice>().like(true, "practice_type", "判断题"));

        Random random = new Random();
        //random.nextInt(questionList.size()+1);
        // 单选题个数
        Integer singleNumber = samplepaper.getSingleNumber();
        // 所有单选题 题数
        int singleListSize = singleList.size();
        // 添加当前试卷的单选题
        SamplePracticeInfo samplePracticeInfo = new SamplePracticeInfo();
        // 设置试卷编号
        samplePracticeInfo.setSamplepaperId(samplepaper.getSampleId());
        int single = 0;
        for (int i = 0; i < singleNumber; i++) {
            // 设置题目ID
            samplePracticeInfo.setPracticeId(singleList.get(random.nextInt(singleListSize)).getPracticeId());
            single += samplePracticeInfoMapper.insert(samplePracticeInfo);
        }

        // 判断题个数
        Integer judgeNumber = samplepaper.getJudgeNumber();
        // 所有判断题 题数
        int judgeListSize = judgeList.size();
        int judge = 0;
        for (int i = 0; i < judgeNumber; i++) {
            // 设置题目ID
            samplePracticeInfo.setPracticeId(judgeList.get(random.nextInt(judgeListSize)).getPracticeId());
            judge += samplePracticeInfoMapper.insert(samplePracticeInfo);
        }

        if ((singleNumber == single) && (judgeNumber == judge)) {
            map.put("info", "success");
        } else {
            map.put("info", "error");
        }
        return map;
    }

    @Override
    public HashMap<String, Object> sampleTest(Samplepaper samplepaper) {
        HashMap<String, Object> map = new HashMap<>();

        // 获取 当前试卷的考题信息
        List<Practice> allPractices = practiceMapper.getAllPractices(samplepaper.getSampleId());
        samplepaper = samplepaperMapper.selectById(samplepaper.getSampleId());
        if (allPractices.size() != 0) {
            map.put("info", "success");
            samplepaper.setSampleList(allPractices);
            map.put("sample", samplepaper);
        } else {
            map.put("info", "error");
        }

        return map;
    }

    @Override
    public HashMap<String, Object> deletePaper(Integer sampleId) {

        HashMap<String, Object> map = new HashMap<>();
        //删除模拟考试题
        int num = samplepaperMapper.deleteById(sampleId);
        //删除中间表的考试题
        int i = samplePracticeInfoMapper.deleteBySampleId(sampleId);
        if (num > 0) {
            map.put("info", "success");
        } else {
            map.put("info", "error");
        }
        return map;
    }
}

